<?php

namespace App\Http\Services\Admin;

use App\Models\Admin\MenuModel;
use App\Models\Admin\RoleModel;
use App\Http\Services\Service;
use Illuminate\Support\Facades\DB;

class RoleService implements Service
{
    /**
     * 列表
     */
    public function index(array $params = []): array
    {
        return RoleModel::all()->toArray();
    }

    /**
     * 分页列表
     */
    public function table(int $page, int $pageSize, array $params): array
    {
        $roleModel = RoleModel::query()
            ->when($params['name'] ?? false, fn($query, $name) => $query->where('name', 'like', $name . '%'))
            ->when($params['slug'] ?? false, fn($query, $name) => $query->where('slug', 'like', $name . '%'));
        $total = (clone $roleModel)->count();
        $list = $roleModel->with('menus')->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
        return compact('total', 'list');
    }

    /**
     * 新增或更新
     * @throws \Throwable
     */
    public function insertOrUpdate(int $id, array $data): array
    {
        DB::beginTransaction();
        $menus = $data['menus'];
        unset($data['menus']);
        try {
            if ($id) {
                RoleModel::query()->where('id', $id)->update($data);
                RoleModel::query()->find($id)->menus()->detach();
            } else {
                $id = RoleModel::query()->insertGetId($data);
            }
            RoleModel::query()->find($id)->menus()->saveMany(MenuModel::query()->whereIn('id', $menus)->get());
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new $e;
        }
        $data['id'] = $id;
        return $data;
    }

    /**
     * 详情
     */
    public function show(int $id): array
    {
        return RoleModel::query()->findOrFail($id)->toArray();
    }

    /**
     * 删除
     * @throws \Throwable
     */
    public function delete(array $ids): void
    {
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id === RoleModel::Role_Admin) continue;
                $roleModel = RoleModel::query()->findOrFail($id);
                $roleModel->menus()->detach();
                $roleModel->delete();
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw $e;
        }
    }
}
